import {
  HttpException,
  Injectable,
  UnauthorizedException,
} from '@nestjs/common';
import { UserService } from '../user/user.service';
import { JwtService } from '@nestjs/jwt';

@Injectable()
export class AuthService {
  constructor(
    private userService: UserService,
    private jwt: JwtService,
  ) {}

  async signin(username: string, password: string) {
    const user = await this.userService.find(username);
    if (user && user.password === password) {
      // 生成token
      const payload = { sub: user.id, username };
      return await this.jwt.signAsync(payload, { privateKey: 'secretKey' });
    }
    throw new UnauthorizedException();
  }
  async signup(username: string, password: string) {
    const res = await this.userService.createUser({
      username,
      password,
    });
    try {
      return res;
    } catch (error) {
      throw new HttpException(error.sqlMessage, 500);
    }
  }
}
